<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./js/axios.js"></script>
  <script src="./js/vue.js"></script>
  <script src="./js/md5.js"></script>
</head>
<body>
  <div id="box">
    <!-- <form id="forms" name="forms" enctype="multipart/form-data" method="post"> -->
      <input type="hidden" v-model="id" name="id">
      商品名: <input type="text"  v-model="name" required name="name"></br><br>
      图片上传: <input type="file" @change="handleFiles" required name="a_picPath"><br><br>
      价格: <input type="text"  v-model="price" required name="price"><br><br>
      库存: <input type="text" v-model="inventory" required name="stock"><br><br>
      <button @click="updataClick">修改</button>
    <!-- </form> -->
    
  </div>
  <script>
    new Vue({
      el:"#box",
      data:{
        id:0,
        name:"",
        price:0.0,
        inventory:"",
        files:"",
        proType1:[],
        proType2:[],
        proType3:[],
        type1: "0",
        type2: "0",
        type3: "0",
      },
      methods:{
        md5Public:async function(objectStr){
          let randomNum = 0;
          //接口拿随机数
          await axios({
              url:"http://localhost:8080/setRedisNum",
              methods:"get"
          }).then(res => {
              randomNum = res.data;
              
          })
          //放到header里的参数 时间戳 随机数 加密的字符串
          //时间戳
          var dateStr = new Date();
          dateStr = Date.now();
              
          //把obj按照key值升序
          let sortObject = function(obj){
              let sorter = function(a,b){
                  return obj[a] - obj[b];
              }
              let keys = Object.keys(obj);
              keys.sort(sorter);
              let res = {};
              keys.forEach(key => {
                  res[key] = obj[key];
              });
              return res;
          }
          //升序的对象
          var sxStr = sortObject(objectStr);
          //把升序的对象转成字符串
          var jsonStr = "";
          for(let obj in objectStr){
              jsonStr += obj+"="+objectStr[obj]+"&";
          }
          //把最后一个&符号切割了
          jsonStr = jsonStr.substr(0, jsonStr.length - 1); 

          //加密字符串
          var str = MD5(jsonStr+randomNum);
          await axios({
              url:"http://localhost:8080/returnInterfaceStr",
              methods:"POST",
              params:objectStr,
              headers:{
                  "TimeStamp":dateStr,
                  "randomNum":randomNum,
                  "encryptionStr":str
              }
          }).then(res => {
              if( res.data == true ){
                  return true;
              }else{
                  return false;
              }
          })
          return true;
      },
        getParameter:function(par){
          //获取当前URL
          var local_url = document.location.href;
          //截取get字符串
          var getstr = local_url.substr(local_url.indexOf('?') + 1)
          //解析成get数组
          var post = getstr.split('&')
          //查找要找到参数（par）
          for ( var i in post) {
              if (post[i].indexOf(par + '=') >= 0) {
                  return post[i].replace(par + '=', '');
              }
          }
          //如果找不到返回false
          return false;
        },
        updataClick:function(){
          let formData=new FormData();
          formData.append("id",this.id);
          formData.append("name",this.name);
          formData.append("a_picPath",this.files);
          formData.append("stock",this.inventory);
          formData.append("price",this.price);
          axios({
            method:"post",
            url:"http://localhost:8080/updateProductToSql",
            headers:{
              'Content-Type':'multipart/form-data'
            },
            data:formData
          }).then(res=>{
            if( this.name == "" ){
              alert("名字不能为空");
              return;
            }
            if( this.price <= 0 ){
              alert("单价不能为0,及负数");
              return;
            }
            if( this.stock <= 0 ){
              alert("库存不能为0,及负数");
              return;
            }

            if(res.data == true){
              window.location="./goodsList.html";
            }else{
              alert("修改失败!请检查是否全部填入");
            }
          })
        },
        //初始化显示要修改的数据
        init:async function(){
          let flag = await this.md5Public({"a1":54,"a2":55,"a3":56});
          if( flag == true ){
            axios.get("http://localhost:8080/getProductListById?id="+this.id).then(res => {
              console.log(res);
              this.name = res.data[0].name;
              this.price = res.data[0].price;
              this.inventory = res.data[0].stock;
            })
          }
          
        },
        handleFiles:function(event){
          this.files = event.target.files[0];
          console.log(this.files);
        }
      },
      created:function(){
        this.id = this.getParameter("id");
        this.init();
      }
    })
  </script>
  
</body>
</html>